﻿using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace B.MESUI.Login.BasicData_UI
{
   
        public partial class GetUserControl : XtraUserControl
        {
            public FlowLayoutPanel QueryPanel { get; private set; }
            public SimpleButton btnQuery, btnReset, btnAdd, btnEdit, btnDelete, btnExport;
            public SimpleButton btnPrev, btnNext, btnFirst, btnLast, btnJump;
            public LabelControl lblPageInfo;
            public TextEdit txtJump;

            // 查询条件类型枚举
            public enum QueryFieldType
            {
                TextBox,         // 文本框
                ComboBox,        // 下拉框
                DateEdit,        // 日期选择
                DateTimeEdit,    // 日期时间选择
                CheckBox,        // 复选框
                RadioGroup,      // 单选组
                SpinEdit,        // 数字输入
                LookUpEdit,      // 高级下拉（可带搜索）
                MemoEdit,        // 多行文本
                ButtonEdit,      // 带按钮的文本框
                TimeEdit         // 时间选择
            }

            // 查询条件描述类
            public class QueryField
            {
                public string FieldName { get; set; }
                public string DisplayName { get; set; }
                public QueryFieldType FieldType { get; set; }
                public object DataSource { get; set; } // 下拉/单选/LookUp的数据源
            }

            // 查询条件配置示例
            public List<QueryField> QueryFields = new List<QueryField>
            {
                new QueryField { FieldName = "CUSTOMER_CODE", DisplayName = "客户编号", FieldType = QueryFieldType.TextBox },
                new QueryField { FieldName = "CUSTOMER_TYPE", DisplayName = "客户类型", FieldType = QueryFieldType.ComboBox, DataSource = new List<string> { "VIP", "普通" } },
                new QueryField { FieldName = "IS_ACTIVE", DisplayName = "是否启用", FieldType = QueryFieldType.CheckBox },
                new QueryField { FieldName = "CREATE_TIME", DisplayName = "创建时间", FieldType = QueryFieldType.DateEdit },
                new QueryField { FieldName = "REMARK", DisplayName = "备注", FieldType = QueryFieldType.MemoEdit }
                // ... 你可以继续添加
            };

            // 查询控件字典
            public Dictionary<string, Control> QueryControls = new Dictionary<string, Control>();

            // 公共属性，便于外部访问表格控件
            public GridControl MainGrid
            {
                get
                {
                    var gridContainer = this.Controls.OfType<Panel>().FirstOrDefault();
                    if (gridContainer != null)
                    {
                        return gridContainer.Controls.OfType<GridControl>().FirstOrDefault();
                    }
                    return null;
                }
            }

            public GetUserControl()
            {
                InitializeComponent();
                InitLayout();
            }

            private void InitLayout()
            {
                // 创建主布局容器：TableLayoutPanel，分两行
                var mainContainer = new PanelControl
                {
                    Dock = DockStyle.Top,
                    Padding = new Padding(0, 0, 0, 0)
                };

                // 查询条件面板（横向排列）
                QueryPanel = new FlowLayoutPanel
                {
                    Dock = DockStyle.Fill,
                    FlowDirection = FlowDirection.LeftToRight,
                    WrapContents = false,
                    AutoSize = true,
                    AutoSizeMode = AutoSizeMode.GrowAndShrink,
                    Margin = new Padding(900,0,0,0),
                };

                // 按钮面板（右侧操作按钮）
                var buttonPanel = new FlowLayoutPanel
                {
                    Dock = DockStyle.Right,
                    FlowDirection = FlowDirection.LeftToRight,
                    WrapContents = false,
                    AutoSize = true,
                    AutoSizeMode = AutoSizeMode.GrowAndShrink,
                    Margin = new Padding(0)
                };

                // 查询和重置按钮
                btnQuery = new SimpleButton { Text = "查询", Width = 90, Height = 40, Margin = new Padding(10, 0, 10, 0) };
                btnReset = new SimpleButton { Text = "重置", Width = 90, Height = 40, Margin = new Padding(10, 0, 10, 0) };

            // 添加到查询面板
            buttonPanel.Controls.Add(btnQuery);
            buttonPanel.Controls.Add(btnReset);

                // 操作按钮
                btnAdd = new SimpleButton { Text = "新增", Width = 90, Height = 40, Margin = new Padding(10, 0, 10, 0) };
                btnEdit = new SimpleButton { Text = "修改", Width = 90, Height = 40, Margin = new Padding(10, 0, 10, 0) };
                btnDelete = new SimpleButton { Text = "删除", Width = 90, Height = 40, Margin = new Padding(10, 0, 10, 0) };
                btnExport = new SimpleButton { Text = "导出", Width = 90, Height = 40, Margin = new Padding(10, 0, 10, 0) };

                buttonPanel.Controls.Add(btnAdd);
                buttonPanel.Controls.Add(btnEdit);
                buttonPanel.Controls.Add(btnDelete);
                buttonPanel.Controls.Add(btnExport);

                // 将查询面板和按钮面板放入主容器
                mainContainer.Controls.Add(QueryPanel);
                mainContainer.Controls.Add(buttonPanel);

                // 使用 TableLayoutPanel 布局（左侧查询 + 右侧按钮）
                var queryTable = new TableLayoutPanel
                {
                    Dock = DockStyle.Top,
                    ColumnCount = 2,
                    RowCount = 1,
                    Height =100,
                    AutoSize = true,
                    AutoSizeMode = AutoSizeMode.GrowAndShrink,
                    Padding = new Padding(10, 10, 10, 0)
                };

               // queryTable.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 70F));
               /// queryTable.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 30F));

                queryTable.Controls.Add(QueryPanel, 0, 0);
                queryTable.Controls.Add(buttonPanel, 1, 0);

                // 创建顶部间隔Panel
                var topSpacer = new Panel
                {
                    Height = 10, // 可根据需要调整高度
                    Dock = DockStyle.Top,
                    BackColor = Color.Transparent // 或 Color.LightGray
                };

                // 创建表格容器
                var gridContainer = new Panel
                {
                    Dock = DockStyle.Fill,
                    Padding = new Padding(0),
                    BackColor = Color.LightBlue, // 调试用，便于观察区域
                    AutoScroll = true, // 启用滚动条
                    AutoScrollMinSize = new Size(2000, 0) // 让Panel足够宽，出现水平滚动条
                };

                // 表格区
                var grid = new GridControl { Dock = DockStyle.Fill };
                var gridView = new GridView();
                grid.MainView = gridView;
                grid.ViewCollection.Add(gridView);
                gridView.OptionsView.ShowGroupPanel = false;
                gridView.OptionsView.ShowColumnHeaders = true; // 显示表头
                gridView.OptionsView.ColumnAutoWidth = false;
            //添加滚动条
            gridView.OptionsView.ShowIndicator = false;
            gridView.Appearance.HeaderPanel.Font = new Font("微软雅黑", 10, FontStyle.Bold);
                gridView.Appearance.HeaderPanel.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                gridView.Appearance.Row.Font = new Font("微软雅黑", 10);
                gridView.RowHeight = 32;
                gridContainer.Controls.Add(grid);

            // 设置滚动条 - 使用最基本的属性
            gridView.OptionsView.ColumnAutoWidth = false; // 禁用列自动宽度以启用水平滚动
            gridView.BestFitColumns();


            // 分页区
            var pagerPanel = new PanelControl
            {
                Dock = DockStyle.Bottom,
                Height = 100,
                AutoSize = false,
               
            };
                var pagerFlow = new FlowLayoutPanel
                {
                    Dock = DockStyle.Left,
                    FlowDirection = FlowDirection.LeftToRight,
                    WrapContents = false,
                    Padding = new Padding(10, 0, 30, 0),
                    AutoSize = false,
                    AutoSizeMode = AutoSizeMode.GrowOnly,
                    AutoScroll = true ,// 启用滚动条
                    Width = 1500
                };

                btnFirst = new SimpleButton { Text = "首页", Width = 90, Height = 40, Margin = new Padding(10, 20, 15, 0) };
                btnPrev = new SimpleButton { Text = "上一页", Width = 90, Height = 40, Margin = new Padding(10, 20, 15, 0) };
                btnNext = new SimpleButton { Text = "下一页", Width = 90, Height = 40, Margin = new Padding(10, 20, 15, 0) };
                btnLast = new SimpleButton { Text = "尾页", Width = 90, Height = 40, Margin = new Padding(10, 20, 15, 0) };
                lblPageInfo = new LabelControl { Text = "第1/1页 共0条", Width = 40, Font = new Font("微软雅黑", 10, FontStyle.Bold), Margin = new Padding(10, 20, 15, 0) };
                txtJump = new TextEdit { Width = 30, Height = 32, Margin = new Padding(10, 20, 15, 0) };
                btnJump = new SimpleButton { Text = "跳转", Width = 90, Height = 40, Margin = new Padding(10,20, 15, 0) };

                pagerFlow.Controls.AddRange(new Control[] { btnFirst, btnPrev, btnNext, btnLast, lblPageInfo, txtJump, btnJump });
                pagerPanel.Controls.Add(pagerFlow);

                // 先添加Grid，再添加分页区
                gridContainer.Controls.Add(pagerPanel); // 先添加GridControl，再添加分页区
                // 再添加表格容器（Dock=Fill）
                this.Controls.Add(gridContainer);
                // 再添加分隔线（Dock=Top）
                this.Controls.Add(topSpacer);
                // 最后添加查询区（Dock=Top）
                this.Controls.Add(queryTable);
            }

            // 动态生成查询区
            public void InitQueryPanel()
            {
                QueryPanel.Controls.Clear();
                foreach (var field in QueryFields)
                {
                    QueryPanel.Controls.Add(new Label() { Text = field.DisplayName + "：", AutoSize = true, Margin = new Padding(10, 8, 0, 0) });
                    Control ctrl = null;
                    switch (field.FieldType)
                    {
                        case QueryFieldType.TextBox:
                            ctrl = new DevExpress.XtraEditors.TextEdit() { Width = 120 };
                            break;
                        case QueryFieldType.ComboBox:
                            var combo = new DevExpress.XtraEditors.ComboBoxEdit() { Width = 120 };
                            if (field.DataSource != null)
                                combo.Properties.Items.AddRange((field.DataSource as IEnumerable<object>).ToArray());
                            ctrl = combo;
                            break;
                        case QueryFieldType.DateEdit:
                            ctrl = new DevExpress.XtraEditors.DateEdit() { Width = 120 };
                            break;
                        case QueryFieldType.DateTimeEdit:
                            var dateTime = new DevExpress.XtraEditors.DateEdit() { Width = 150 };
                            dateTime.Properties.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
                            dateTime.Properties.DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                            dateTime.Properties.EditFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
                            dateTime.Properties.EditFormat.FormatType = DevExpress.Utils.FormatType.DateTime;
                            ctrl = dateTime;
                            break;
                        case QueryFieldType.CheckBox:
                            ctrl = new DevExpress.XtraEditors.CheckEdit();
                            break;
                        case QueryFieldType.RadioGroup:
                            var radio = new DevExpress.XtraEditors.RadioGroup();
                            if (field.DataSource != null)
                            {
                                var items = (field.DataSource as IEnumerable<object>).ToArray();
                                foreach (var item in items)
                                    radio.Properties.Items.Add(new DevExpress.XtraEditors.Controls.RadioGroupItem(item, item.ToString()));
                            }
                            ctrl = radio;
                            break;
                        case QueryFieldType.SpinEdit:
                            ctrl = new DevExpress.XtraEditors.SpinEdit() { Width = 120 };
                            break;
                        case QueryFieldType.LookUpEdit:
                            var lookup = new DevExpress.XtraEditors.LookUpEdit() { Width = 120 };
                            if (field.DataSource != null)
                                lookup.Properties.DataSource = field.DataSource;
                            ctrl = lookup;
                            break;
                        case QueryFieldType.MemoEdit:
                            ctrl = new DevExpress.XtraEditors.MemoEdit() { Width = 200, Height = 40 };
                            break;
                        case QueryFieldType.ButtonEdit:
                            ctrl = new DevExpress.XtraEditors.ButtonEdit() { Width = 120 };
                            break;
                        case QueryFieldType.TimeEdit:
                            ctrl = new DevExpress.XtraEditors.TimeEdit() { Width = 120 };
                            break;
                    }
                    if (ctrl != null)
                    {
                        QueryPanel.Controls.Add(ctrl);
                        QueryControls[field.FieldName] = ctrl;
                    }
                }
            }

            // 获取所有查询条件的值
            public Dictionary<string, object> GetQueryValues()
            {
                var dict = new Dictionary<string, object>();
                foreach (var pair in QueryControls)
                {
                    if (pair.Value is DevExpress.XtraEditors.TextEdit txt)
                        dict[pair.Key] = txt.Text;
                    else if (pair.Value is DevExpress.XtraEditors.ComboBoxEdit cmb)
                        dict[pair.Key] = cmb.Text;
                    else if (pair.Value is DevExpress.XtraEditors.DateEdit date)
                        dict[pair.Key] = date.EditValue;
                    else if (pair.Value is DevExpress.XtraEditors.CheckEdit chk)
                        dict[pair.Key] = chk.Checked;
                    else if (pair.Value is DevExpress.XtraEditors.RadioGroup radio)
                        dict[pair.Key] = radio.EditValue;
                    else if (pair.Value is DevExpress.XtraEditors.SpinEdit spin)
                        dict[pair.Key] = spin.Value;
                    else if (pair.Value is DevExpress.XtraEditors.LookUpEdit lookup)
                        dict[pair.Key] = lookup.EditValue;
                    else if (pair.Value is DevExpress.XtraEditors.MemoEdit memo)
                        dict[pair.Key] = memo.Text;
                    else if (pair.Value is DevExpress.XtraEditors.ButtonEdit btnEdit)
                        dict[pair.Key] = btnEdit.Text;
                    else if (pair.Value is DevExpress.XtraEditors.TimeEdit time)
                        dict[pair.Key] = time.EditValue;
                }
                return dict;
            }

            public void SetQueryFields(List<QueryField> fields)
            {
                this.QueryFields = fields;
                InitQueryPanel();
            }
        }
    }
